
namespace SB2.Application
{
    /// <summary>
    /// 动态函数
    /// </summary>
    [ApiDescriptionSettings("Dynamic")]
    [Route("api/dynamic/function")]
    [AllowAnonymous]
    public class DynamicFunctionService : IAppAuthorizedService
    {
        DynamicFunctionRepository repository;
        public DynamicFunctionService(DynamicFunctionRepository repository)
        {
            this.repository = repository;
        }
        /// <summary>
        /// 执行动态函数
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<DynamicFunctionExcResponse> Exc(DynamicFunctionExcRequest dto)
        {
            try
            {

                var res = await new DynamicFunctionSrv(dto.Id).RunAsync(dto.Param);
                return DynamicFunctionExcResponse.OK(res);
            }
            catch (Exception e)
            {

                return DynamicFunctionExcResponse.Error(e.Message);
            }
        }
    }
    /// <summary>
    /// 动态函数执行参数
    /// </summary>
    public class DynamicFunctionExcRequest
    {
        /// <summary>
        /// 函数id
        /// </summary>
        /// <value></value>
        [Required]
        public long Id { get; set; }
        /// <summary>
        /// 函数参数
        /// </summary>
        /// <value></value>
        public string Param { get; set; }

    }
    /// <summary>
    /// 动态函数执行返回参数
    /// </summary>
    public class DynamicFunctionExcResponse
    {
        /// <summary>
        /// 函数是否顺利执行
        /// </summary>
        /// <value></value>
        public bool Exccuted { get; set; }
        /// <summary>
        /// 如果执行失败，会返回对应的失败信息
        /// </summary>
        /// <value></value>
        public string Msg { get; set; }
        /// <summary>
        /// 函数执行返回结果
        /// </summary>
        /// <value></value>
        public object Result { get; set; }
        /// <summary>
        /// 成功
        /// </summary>
        /// <param name="Result"></param>
        /// <returns></returns>
        public static DynamicFunctionExcResponse OK(object Result)
        {

            return new DynamicFunctionExcResponse
            {
                Exccuted = true,
                Result = Result
            };
        }
        /// <summary>
        /// 失败
        /// </summary>
        /// <param name="Msg"></param>
        /// <returns></returns>
        public static DynamicFunctionExcResponse Error(string Msg)
        {

            return new DynamicFunctionExcResponse
            {
                Exccuted = false,
                Msg = Msg
            };
        }

    }
}